<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/25
 * Time: 11:26
 */

?>


<?php

require_once "../config/config.php";

//因为每次操作数据库都要连接，所以干脆也封装起来
function connect(){
    //1. 连接数据库服务
    $connect = mysqli_connect(DB_HOST,DB_USER,DB_PWD);
    //2. 选择数据库
    mysqli_select_db($connect,DB_NAME);
    //3. 有必要的时候设置一下编码 --- 一般都会设置
    mysqli_set_charset($connect,"utf8");

    //返回连接
    return $connect;
}


//封装一个用于查询的方法

function query($sql){
    //1. 连接数据库服务
    $connect = mysqli_connect("127.0.0.1","root","root");

    //2. 选择数据库
    mysqli_select_db($connect,"alibaixiu");

    //3. 有必要的时候设置编码格式 --- 一般都会设置
    mysqli_set_charset($connect,"utf8");

    //4. 准备操作数据库的sql语句
//    $sql = "SELECT * FROM users WHERE email = '{$email}'";

    //5. 执行sql代码并接受结果
    $res = mysqli_query($connect,$sql);

    //得到查询结果之后，看看里面有没有数据 --- 一般会把结果集转换为二维数组

    $arr = array();

    //循环取出结果集里面的每行数据 --- 以关联数组的形式返回
    while ($row = mysqli_fetch_assoc($res)){
        $arr[] = $row;
    }

    //要把查询的结果以二维数组的形式返回
    return $arr;

}


//封装插入操作函数
function insert($arr,$table){
    $keys = array_keys($arr);
    $value = array_values($arr);

    $sql = "INSERT INTO {$table} (" . implode(",",$keys) . ") values('" . implode("','",$value) ."')";

    $connect = connect();
    $res = mysqli_query($connect,$sql);

    return $res;
}


//封装更新操作
function update($table,$arr,$id){
    $connect = connect();

    $sql = " UPDATE {$table} SET ";

    foreach ($arr as $key => $value) {
        $sql .= $key . "='" . $value . "',";
    }

    //删除多余的逗号
    $sql = substr($sql,0,-1);

    //拼接修改的条件
    $sql .= " WHERE id = {$id} ";

    //执行$sql语句
    $res = mysqli_query($connect,$sql);

    //返回结果
    return $res;
}


//封装删除操作函数
function deleteById($table,$id){

    $sql = " DELETE FROM {$table} WHERE id = {$id} ";

    $connect = connect();

    $res = mysqli_query($connect,$sql);

    return $res;
}


//封装执行数据库操作
function execute($sql){
    $connect = connect();

    $res = mysqli_query($connect,$sql);

    return $res;
}

?>
